package cn.wen.base.view.limit;

import android.content.Context;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;

/**
 * 访淘宝限时换购的头部
 */

public class LimitTabView extends ViewGroup {
    private int mItemCount = 5;// 一行Item的个数
    private int mScreenWidth;//屏幕的宽度
    private int mItemWidth;// Item的宽度
    private int mStartX;// 开始摆放子View的位置

    public LimitTabView(Context context) {
        this(context, null);
    }

    public LimitTabView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public LimitTabView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        mScreenWidth = outMetrics.widthPixels;
        mItemWidth = mScreenWidth / mItemCount;
        mStartX = mItemWidth * (mItemCount / 2);
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int count = getChildCount();
        // 自己的宽高
        int width = mItemWidth * count + mStartX * 2;//左右各多一个开始的位置
        int height = MeasureSpec.getSize(heightMeasureSpec);
        for (int i = 0; i < count; i++) {
            View child = getChildAt(i);
            measureChild(child, widthMeasureSpec, heightMeasureSpec);
        }
        setMeasuredDimension(width, height);
    }


    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int count = getChildCount();
        int left = mStartX;
        for (int i = 0; i < count; i++) {
            View child = getChildAt(i);
            LayoutParams params = child.getLayoutParams();
            params.width = mItemWidth;
            params.height = getMeasuredHeight();
            child.setLayoutParams(params);
            child.layout(left, 0, left + mItemWidth, getMeasuredHeight());
            left += mItemWidth;
        }
    }

    public int getItemWidth() {
        return mItemWidth;
    }

    /**
     * 设置一屏Item的个数
     */
    public void setItemCount(int itemCount) {
        this.mItemCount = itemCount;
        mItemWidth = mScreenWidth / mItemCount;
        mStartX = mItemWidth * (mItemCount / 2);
    }
}
